<script setup lang="ts">
import { ref, onMounted, toRaw, reactive, watch } from 'vue'
import { useRoute, useRouter } from "vue-router";
import { classesSelect } from '../../stores/api/class'
import { teachHomeworkUser, teachHomeworkCreate, teachHomeworkUpdate } from '../../stores/api/homework'
import { message } from 'ant-design-vue';
import type { UnwrapRef } from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import { useCounterStore } from '../../stores/counter'
import type { UploadProps } from 'ant-design-vue';
import { PictureOutlined, LoadingOutlined, UploadOutlined } from '@ant-design/icons-vue';
import { upload } from '../../utils/upload' // 引入js
import { ImgUrlPrefix } from '../../utils/config'
// import WangEditor from '../components/wangEditor.vue'
const router:any = useRouter()
const route:any = useRoute()
const fileList = ref<UploadProps['fileList']>([])
const imgList:any = ref([])
    // {
    //             uid: '-1',
    //             name: '1755070063338_boa6xj.png',
    //             status: 'done',
    //             url: 'https://static.xueqianban.vip/images/console/20250813/1755070063338_boa6xj.png',
    //         }
const uploading = ref<boolean>(false);
const user_list = ref([])
const store = useCounterStore()

interface FormState {
    content: string;
    title: string;
    classes_id: Array<string> | number;
    annex: Array<string>;
    img: Array<string>;
    deadline: string;
}
const formRef = ref();
const labelCol = { span: 3 };
const wrapperCol = { span: 24 };
const formState: UnwrapRef<FormState> = reactive({
    content: '', // 内容
    title: '', // 标题
    classes_id: [], // 班级
    annex: [], // 上传附件文件
    img: [], // 图片素材'images/console/20250813/1755070063338_boa6xj.png'
    deadline: '', // 截止时间
});
const rules: Record<string, Rule[]> = {
  title: [
    { required: true, message: '请输入标题', trigger: 'change' },
  ]
};
// 班级下拉列表
const getClassesSelectr = () => {
    classesSelect({}, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            user_list.value = res.data
        } else {
            message.error(res.message);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}
// 提交
const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log('values', formState, toRaw(formState));
      if(route.query.id) {
        console.log('编辑')
        updateHomework()
      } else {
        console.log('添加')
        createHomework()
      }
    })
    .catch(error => {
      console.log('error', error);
    });
};
// 取消
const resetForm = () => {
  formRef.value.resetFields();
//   emits("backUpdateChange2", { isShowUpdatePw: false});
  router.go(-1)
};

// 调用发布作业接口
const createHomework = () => {
    let attachment = [formState.img, formState.annex]
    let obj = {
        class_id: Number(route.query.class_id),
        course_id: Number(route.query.course_id),
        classes_id: formState.classes_id,
        "title": formState.title,
        "attachment": attachment ? JSON.stringify(attachment) : '',
        "desc": formState.content,
        "deadline": formState.deadline ? store.getTimestamp(formState.deadline) : '' // 截止时间
    }
    console.log(obj)
    teachHomeworkCreate(obj, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            message.success('发布成功');
            formRef.value.resetFields();
            fileList.value = []
            formState.annex = []
            formState.img = []
            imgList.value = []
            router.go(-1)
        } else {
            message.error(res.msg);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 调用编辑作业接口
const updateHomework = () => {
    let attachment = [formState.img, formState.annex]
    let obj = {
        id: Number(route.query.id),
        class_id: Number(route.query.class_id),
        course_id: Number(route.query.course_id),
        classes_id: formState.classes_id,
        "title": formState.title,
        "attachment": attachment ? JSON.stringify(attachment) : '',
        "desc": formState.content,
        "deadline": formState.deadline ? store.getTimestamp(formState.deadline) : '' // 截止时间
    }
    console.log(obj)
    teachHomeworkUpdate(obj, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            message.success(res.message);
            formRef.value.resetFields();
            fileList.value = []
            formState.annex = []
                formState.img = []
                imgList.value = []
            router.go(-1)
        } else {
            message.error(res.msg);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 上传附件
const beforeUpload: UploadProps['beforeUpload'] = file => {
  const isPNG = file.type === 'image/png';
//   if (!isPNG) {
//     message.error(`${file.name} is not a png file`);
//   }
//   return isPNG || Upload.LIST_IGNORE;
  return true
};
// 附件上传
const handleUpload = (data) => {
    console.log('上传11')
    console.log(data,'handleUpload')
    upload(data.file,res => {
      console.log(res,'ddddd')
      if(res) {
            const startIndex = res.indexOf('/') + 1;
            const urls = res.substring(startIndex);
            formState.annex = [...formState.annex, urls]
            fileList.value.forEach(item => {
                if(item.uid == data.file.uid){
                    item.status = 'done'
                }
            })
            console.log(urls, fileList.value)
      } else {
        
      }
      uploading.value = false;
    }).catch(err => {
    })
}
// 删除
const handleRemov = (file) => {
  console.log('file',file)
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  formState.annex.splice(index,1)
}

// 图片上传--删除
const handleRemoveImg: UploadProps['onRemove'] = file => {
    console.log('file',file)
  const index = imgList.value.indexOf(file);
  const newFileList = imgList.value.slice();
  newFileList.splice(index, 1);
  formState.img.splice(index, 1)
  imgList.value = newFileList;
};
// 图片上传之前
const beforeUploadImg: UploadProps['beforeUpload'] = file => {
//   imgList.value = [...(imgList.value || []), file];
//   console.log(imgList.value)
  return true;
};
// 图片上传
const handleUploadImg = (data) => {
//   const formData = new FormData();
//   imgList.value.forEach((file: UploadProps['fileList'][number]) => {
//     formData.append('files[]', file as any);
//   });
  uploading.value = true;
  console.log(imgList.value, data,'handleUpload')
  upload(data.file,res => {
      console.log(res,'ddddd')
      if(res) {
            const startIndex = res.indexOf('/') + 1;
            const urls = res.substring(startIndex);
            formState.img.push(urls)
            imgList.value.push({
                uid: '-1',
                name: urls.substring(urls.lastIndexOf('/') + 1),
                status: 'done',
                url: getImgUrl(urls),
            })
            console.log(urls)
      }
      uploading.value = false;
  })
};

// 图片地址拼接
const getImgUrl = (val) => {
    const url = ImgUrlPrefix(val)
    return url
}
// watch(route.query.data, (newVal:any, oldValue:any) => {
//    console.log('data',newVal, oldValue)
// //    formState.title = newVal.title
// //    formState.permission = newVal.permission
// //    formState.thumbnail = newVal.thumbnail
// })
onMounted(() => {
    getClassesSelectr()
    console.log(route.query.data)
    if(route.query.data) {
        let obj = JSON.parse(route.query.data)
        formState.content = obj.desc // 内容
        formState.title = obj.title  // 标题
        formState.classes_id = obj.classes_id // 班级       
        formState.deadline = obj.deadline // 截止时间
        if(obj.attachment.length > 0 && Array.isArray(obj.attachment[0])) {
            for(let i = 0;i < obj.attachment.length; i++) {
                if(i == 0) {
                    formState.img = obj.attachment[0] || []
                    let array2 = obj.attachment[0] || []
                    let arrImg = array2.map(item => {
                        return {
                            uid: '-1',
                            name: item.substring(item.lastIndexOf('/') + 1),
                            status: 'done',
                            url: getImgUrl(item),
                        }
                    })
                    console.log(arrImg,'arrImg')
                    imgList.value = arrImg
                }
                if(i == 1) {
                    formState.annex = obj.attachment[1] || [] // 上传附件文件
                    let array = obj.attachment[1] || []
                    let arr2 = array.map(item => {
                        return { name: item.substring(item.lastIndexOf('/') + 1), status: 'done', url: getImgUrl(item), uid: '' }
                    })
                    console.log(arr2,'arr2')
                    fileList.value = arr2
                }
            }
        } else if(obj.attachment.length > 0 && !Array.isArray(obj.attachment[0])) {
            formState.annex = obj.attachment
            let array = obj.attachment || []
            let arr2 = array.map(item => {
                return { name: item.substring(item.lastIndexOf('/') + 1), status: 'done', url: getImgUrl(item), uid: '' }
            })
            console.log(arr2,'arr2')
            fileList.value = arr2
        }
    }
});
</script>

<template>
  <div class="start-live-room">
    <a-card class="top-content-p" title="发布作业" style="width: 100%">
        <div class="live-left">
            <a-form
                ref="formRef"
                :model="formState"
                :rules="rules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-form-item ref="title" label="标题" name="title">
                    <a-input v-model:value="formState.title" class="input-item-dd" placeholder="请输入标题" />
                </a-form-item>
                <!-- <a-form-item label="发布类型" name="type">
                    <a-select v-model:value="formState.type" placeholder="请选择发布类型">
                        <a-select-option :value="10">全部用户</a-select-option>
                        <a-select-option :value="20">部分用户</a-select-option>
                    </a-select>
                </a-form-item> -->
                <a-form-item label="班级" name="classes_id">
                    <a-select v-model:value="formState.classes_id" placeholder="请选择班级" :mode="route.query.id ? '' : 'multiple'">
                        <a-select-option :value="item.id" v-for="(item, index) in user_list" :key="item.id">{{item.name}}</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item name="deadline" label="截止时间">
                    <a-date-picker
                        v-model:value="formState['deadline']"
                        :disabled-date="store.disabledDate"
                        :disabled-time="store.disabledDateTime"
                        show-time
                        showNow
                        placeholder="请选择截止时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </a-form-item>
                <a-form-item label="图片素材" name="img">
                    <a-upload class="cover-g" name="avatar" accept=".png,.jpg,.webp,.gif,.jpeg,.svg" list-type="picture-card" :file-list="imgList" :before-upload="beforeUploadImg" @remove="handleRemoveImg" :customRequest="handleUploadImg">
                        <div>
                            <loading-outlined v-if="uploading"></loading-outlined>
                            <PictureOutlined v-else :style="{fontSize: '22px'}" />
                            <div class="ant-upload-text">上传图片</div>
                        </div>
                    </a-upload>
                </a-form-item>
                <a-form-item name="annex" label="附件">
                    <a-upload
                        v-model:file-list="fileList"
                        :before-upload="beforeUpload"
                        :customRequest="handleUpload"
                        @remove="handleRemov"
                        accept=".doc,.docx,.pdf,.xlsx,.xls"
                    >
                        <a-button>
                            <upload-outlined></upload-outlined>
                            上传附件
                        </a-button>
                    </a-upload>
                </a-form-item>
                <a-form-item ref="content" label="描述" name="content">
                    <a-textarea
                        v-model:value="formState.content"
                        placeholder="请输入描述"
                        :auto-size="{ minRows: 4}"
                    />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 24, offset: 4 }" style="text-align: center;">
                    <a-button class="btn-ss" type="primary" @click="onSubmit">提 交</a-button>
                    <a-button style="margin-left: 10px" @click="resetForm">返 回</a-button>
                </a-form-item>
            </a-form>
        </div>
    </a-card>
  </div>
</template>

<style scoped>
.start-live-room{
   display: flex;
   color: #333;
   /* background-color: rgba(22,24,35,1); */
}
.top-content-p{
    border-radius: initial;
}
.live-left{
   flex: 3;
   width: 80%;
   min-width: 230px;
   margin: auto;
   overflow: hidden;
   padding:0 15px;
}
.live-video{
  width: 100%;
  height: 100%;
  object-fit: cover; /* 确保视频撑满父容器 */
}
.basic-info{
    display: flex;
    color: #999;
}
.cover-img{
    width: 50px;
    border-radius: 8px;
}
.cover-g{
    /* background-color: rgb(51,52,63); */
    width: 100%;
    /* height: 132px; */
    line-height: 26px;
    /* text-align: center; */
    padding: 10px 0;
    border-radius: 10px;
}
.cover-image{
    width: 100%;
    height: 100%;
}
.cover-image img{
    width: 100%;
    height: 100%;
}
.ant-upload-text{
    font-size: 14px;
}
.input-item-dd{
    /* height: 30px; */
    /* padding-top: 0; */
    /* background-color: transparent; */
    font-size: 14px; /* 占位符字体大小 */
    /* border:none; */
    /* outline: none; */
    color: #000;
}
.input-item-dd::placeholder {
  font-size: 14px; /* 占位符字体大小 */
  color: #999; /* 占位符字体颜色 */
}
.type-item{
  padding-left:10px;
  margin-top: 20px;
}
.type-s{
    padding: 5px 15px;
    margin-right: 10px;
    border-radius: 10px;
    cursor: pointer;
}
.active{
    background-color: rgb(51,52,63);
}

.positin-boottom{
    position: absolute;
    bottom: 10px;
    width: 94%;
}
.bottom-item-a{
    width:100%;
   display: flex;
   justify-content: space-between;
   align-items: center;
   color: #fff;
   background-color: #080808;
   padding: 8px 15px;
   border-radius: 10px;
}
.btn-ss{
    background-color: #fe5d26;
    height: 34px;
}
.btn-ss:hover{
    background-color: #fe5d26;
}
.live-right{
    color: #fff;
   flex:1;
   position:relative;
   /* background-color: rgb(37,38,50); */
   padding-right: 15px;
}
.live-right-list{
    background-color: rgb(51,52,63);
    padding: 10px 20px;
    height: 22vh;
    border-radius: 10px;
    overflow-y: auto;
}
.live-item{
   display: flex;
   align-items: center;
   justify-content: center;
   color: #898687;
   margin-top: 10px;
}
.live-num{
    line-height: 30px;
    margin-bottom: 20px;
}
.ranking{
    margin-right: 30px;
}
.nick-name{
    margin:0 20px 0 10px;
}
.img-avatar{
    width: 35px;
    height: 35px;
    border-radius: 50%;
}
.grade{
    width: 30px;
}

.live-message{
    padding: 10px 20px;
    background-color: rgb(37,38,50);
    height: 70vh;
    overflow-y: auto;
}
.msg-item{
    display: flex;
    align-items: flex-start;
    margin-top: 8px;
}
.msg-grade{
    width: 40px;
}
.name{
 color: #8ce7ff;
 margin:0 10px;
}
.msg-content{
    line-height: 25px;
}
.bottom-contt{
    position: absolute;
    bottom: 0;
    width: 100%;
    /* background-color: rgb(37,38,50); */
}
.bottom-send{
    display: flex;
    align-items: center;
    color: #fff;
    background-color: rgb(65,66,76);
    margin: 10px 15px 10px 0;
    padding: 8px;
    border-radius: 10px;
}
.send-input{
    background-color: rgb(65,66,76);
    font-size: 16px; /* 占位符字体大小 */
    border:none;
    color: #fff;
}
.send-input::placeholder {
  font-size: 14px; /* 占位符字体大小 */
  color: #999; /* 占位符字体颜色 */
}
.read-the-docs {
  color: #888;
}
</style>